import os
import traceback
import logging
from PyPDF2 import PdfReader, PdfWriter
from config import Config

# 设置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)


def save_single_page(page, output_path):
    """
    保存单页PDF（用于备份）
    :param page: Page对象
    :param output_path: 输出路径
    :return: 操作是否成功
    """
    try:
        writer = PdfWriter()
        writer.add_page(page)
        with open(output_path, "wb") as f:
            writer.write(f)
        logger.info(f"💾 单页保存成功：{os.path.basename(output_path)}")
        return True
    except Exception as e:
        logger.error(f"❌ 单页保存失败：{os.path.basename(output_path)}")
        logger.error(f"📝 错误原因：{str(e)}")
        return False


def replace_page_in_pdf(original_pdf_path, page_to_insert, target_page_idx, output_path):
    """
    替换PDF中指定位置的页面（删旧页+插新页）
    :param original_pdf_path: 原始PDF路径
    :param page_to_insert: 要插入的页面对象
    :param target_page_idx: 目标页面索引
    :param output_path: 输出路径
    :return: 操作是否成功
    """
    original_file = os.path.basename(original_pdf_path)
    target_page_num = target_page_idx + 1
    logger.info(f"\n🔄 开始替换页面：")
    logger.info(f"📄 目标文件：{original_file}")
    logger.info(f"📑 替换操作：删除第{target_page_num}页旧页 → 插入新页")
    logger.info(f"💾 输出路径：{output_path}")

    try:
        reader = PdfReader(original_pdf_path)
        total_pages = len(reader.pages)

        if target_page_idx < 0 or target_page_idx >= total_pages:
            logger.error(f"❌ 替换失败：无效的替换位置！文件共{total_pages}页，目标索引{target_page_idx}")
            return False

        old_page_text = reader.pages[target_page_idx].extract_text() or "无文本"
        logger.info(f"⚠️ 待删除旧页文本（前80字符）：{old_page_text[:80]}...")

        writer = PdfWriter()
        # 写入替换位置之前的页面
        for i in range(target_page_idx):
            writer.add_page(reader.pages[i])
        # 写入新页面
        writer.add_page(page_to_insert)
        # 写入替换位置之后的页面
        for i in range(target_page_idx + 1, total_pages):
            writer.add_page(reader.pages[i])

        if os.path.exists(output_path):
            os.remove(output_path)
        with open(output_path, "wb") as f:
            writer.write(f)
        
        new_reader = PdfReader(output_path)
        logger.info(f"✅ 页面替换成功！最终文件页数：{len(new_reader.pages)}（替换前后页数一致）")
        return True
    except Exception as e:
        logger.error(f"❌ 页面替换失败！")
        logger.error(f"📝 错误原因：{str(e)}")
        traceback.print_exc()
        return False